package com.yusys.jin.blog.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yusys.jin.blog.controller.ex.FileContentTypeException;
import com.yusys.jin.blog.controller.ex.FileIsEmptyException;
import com.yusys.jin.blog.controller.ex.FileSizeException;
import com.yusys.jin.blog.controller.ex.SavePictureException;
import com.yusys.jin.blog.controller.ex.VerifiedcodeIsNullException;
import com.yusys.jin.blog.controller.ex.VerifiedcodeIsWrongException;
import com.yusys.jin.blog.entity.Picture;
import com.yusys.jin.blog.entity.User;
import com.yusys.jin.blog.service.IUserService;
import com.yusys.jin.blog.util.ResponseResult;

/**
 * 用户控制器层
 *
 * @author jin
 */

@RestController
@RequestMapping("/users")
public class UserController extends BaseController {
    @Autowired
    IUserService service;
    /**
     * 允许上传的文件类型的集合
     */
    public static final List<String> CONTENT_TYPE = new ArrayList<String>();
    public static final long UPLOAD_MAX_SIZE = 1 * 1024 * 1024;
    public static final String UPLOAD_DIR = "upload";

    static {
        CONTENT_TYPE.add("image/jpeg");
        CONTENT_TYPE.add("image/png");
        CONTENT_TYPE.add("image/gif");
        CONTENT_TYPE.add("image/bmp");
    }

    @PostMapping("/reg")
    public ResponseResult<Void> handle_reg(String username, String password, @RequestParam(value = "code") String code, String email,
                                           HttpSession session) {
        String verifiedCode = (String) session.getAttribute("mailcode");
        User user = new User();
        user.setUserName(username);
        user.setPassWord(password);
        user.setEmail(email);
        if (code == null || verifiedCode == null) {
            throw new VerifiedcodeIsNullException("没有发送验证码或者输入验证码为空");
        }
        code = code.toUpperCase();                            //不区分大小写
        verifiedCode = verifiedCode.toUpperCase();
        if (!code.equals(verifiedCode)) {
            throw new VerifiedcodeIsWrongException();
        }
        service.reg(user);
        ResponseResult<Void> rr = new ResponseResult<Void>();
        rr.setState(200);
        rr.setMessage("注册成功");
        return rr;
    }

    @PostMapping("/login")
    public ResponseResult<Void> handle_login(HttpServletRequest request, String username, String password, String verifiedcode) {
        System.err.println("开始登陆");
        HttpSession session = request.getSession();
        if (verifiedcode == null) {
            throw new VerifiedcodeIsNullException("验证码不能为空");
        }
        String code = (String) session.getAttribute("code");
        verifiedcode = verifiedcode.toUpperCase();

        if (!verifiedcode.equals(code)) {
            throw new VerifiedcodeIsWrongException("验证码错误");
        }
        System.err.println("开始获取用户ip");
        String ip = request.getRemoteAddr();
        System.err.println("用户ip为：" + ip);
        User user = new User();
        user.setUserName(username);
        user.setPassWord(password);
        service.login(user, session);
        System.err.println("begin to insert into session the username");
        session.setAttribute("user", username);
        System.err.println("insert successfully");
        ResponseResult<Void> rr = new ResponseResult<Void>();
        rr.setState(200);
        rr.setMessage("登录成功");
        return rr;
    }

    @GetMapping("/checkusername")
    public ResponseResult<Void> checkusername(String username) {
        System.err.println("开始检测用户名可用性");
        service.checkusername(username);
        System.err.println("检测完毕");
        return new ResponseResult<Void>(200, "用户名可用");
    }

    @PostMapping("/upload")
    public ResponseResult<String> changeAvatar(HttpServletRequest request,
                                               @RequestParam("avatar") MultipartFile file,
                                               int check,  //文件大小和数据库中文件一致时 确认是否上传  默认为0
                                               int state
    ) {
        System.out.println("请求发送成功");
        HttpSession session = request.getSession();
        Integer uid = getUidFromSession(session);
        String size = file.getSize() + "";
        System.out.println("文件为" + file.getName() + " 大小为" + size);
        if (file.isEmpty()) {
            throw new FileIsEmptyException("上传文件为空");
        }
        if (!CONTENT_TYPE.contains(file.getContentType())) {
            throw new FileContentTypeException("不支持的上传类型");
        }
        if (file.getSize() > UPLOAD_MAX_SIZE) {
            System.err.println("过大");
            throw new FileSizeException("上传文件大小超过范围");
        }
        //*********************************************************//
        String serverPath = Thread.currentThread().getContextClassLoader().getResource("").toString();
        int beginIndex = serverPath.indexOf("/");
        int lastIndex = serverPath.indexOf("target/classes/");
        serverPath = serverPath.substring(beginIndex, lastIndex);
        //*********************************************************// 获取绝对路径
        //*********************************************************//
        System.err.println("绝对路径：" + serverPath + "\\src\\main\\resources\\static");
        File parent = new File(serverPath + "\\src\\main\\resources\\static", UPLOAD_DIR);
        System.err.println(parent.getAbsolutePath());
        System.err.println(parent.exists());
        if (!parent.exists()) {
            parent.mkdir();
            System.err.println("新建文件夹成功");
        }
        //*********************************************************//建立头像图片存放文件夹
        String oringFileName = file.getOriginalFilename();
        String suffix = "";
        int index = oringFileName.lastIndexOf(".");
        if (index != -1) {
            suffix = oringFileName.substring(index);
        }
        System.err.println(suffix);
        String fileName = UUID.randomUUID() + suffix;
        //*********************************************************//生成存储名称
        System.err.println("图片存储名称：" + fileName);
        Picture p = new Picture();

        p.setUid(uid);
        p.setPicturename(fileName);
        p.setSize(size);
        p.setState(state);
        service.updateAvatar(p, check, file, parent);   //将图片名称交给业务层处理
//		try {
//			file.transferTo(new File(parent,fileName));
//		} catch (Exception e) {
//			throw new SavePictureException("写入图片文件失败，请联系管理员处理");
//		}

        ResponseResult<String> rr = new ResponseResult<String>();
        rr.setState(200);
        rr.setMessage("上传成功");
        rr.setData(fileName);
        return rr;
    }

    @GetMapping("getAvatar")
    public ResponseResult<String> getAvartar(Integer state, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Integer uid = getUidFromSession(session);
        System.err.println(uid);
        String fileName = service.findUsersAvataar(state, uid);
        ResponseResult<String> rr = new ResponseResult<String>();
        rr.setData(fileName);
        rr.setState(200);
        return rr;
    }
}
